/**
 * 系统设置
 * @author hanson
 */
define(['jquery', 'jquery-validate-messages_zh', 'public/js/fileUtil'], function($, Validate, FileUtil){
	
	var Page = {}, DOM;
	
	function init(){
		DOM = {
				form: $('#form'),
				btnSubmit: $('#btnSubmit'),
				inpLogo: $('.inpLogo'),
				btnChooseFile: $('.btnChooseFile'),
				imgFile: $('#imgFile'),
				imgContent: $('#imgContent')
		}
	}
	
	Page.main = function(){
		init();
		handleEvent();
	}
	
	function handleEvent(){
		// 表单校验
		DOM.form.validate({
			rules : {
				siteName: {required: true},
				title1: {required: true},
				title2: {required: true},
				siteUrl: {
					required: true,
					pattern: /^(http:\/\/|https:\/\/).*$/i
				},
				siteKeywords: {required: true},
				siteDescription: {required: true},
				//logo: {required: true},
				email: "email",
				siteCloseMessage: "required",
				largeProductImageWidth: {
					required: true,
					integer: true,
					min: 1
				},
				largeProductImageHeight: {
					required: true,
					integer: true,
					min: 1
				},
			},
		});
		
		// 选择logo文件
		DOM.btnChooseFile.click(function(){
			 DOM.imgFile.click();
		});
		
		//预览图片
        DOM.imgFile.change(function () {
            //获取文件
            var file = DOM.imgFile.get(0).files[0];
            //创建读取文件的对象
            var reader = new FileReader();
            //创建文件读取相关的变量
            var img;

            //为文件读取成功设置事件
            reader.onload = function (e) {
//            alert('文件读取完成');
            	img = e.target.result;
                DOM.imgContent.attr('src', img);
            };

            //正式读取文件
            reader.readAsDataURL(file);
        });
		
		// 提交表单
		DOM.btnSubmit.click(function(){
			if(DOM.form.valid()){
				var file = DOM.imgFile.get(0).files[0];
	            var data;
	            FileUtil.upload(file, function (rs) {
	                data = rs;
	            });
	            console.log('data', data);
	            DOM.inpLogo.val(data.path);
				DOM.form.submit();
			}
		});
	}
	
	return Page;
});